package com.nullpointer.playerinfo.bukkit;

import java.io.File;
import java.sql.SQLException;

import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;

import com.magic0610.MagicYaml.MagicYaml;
import com.magic0610.MagicYaml.YamlConfig;
import com.nullpointer.playerinfo.common.Base;
import com.nullpointer.playerinfo.common.Methods;
import com.nullpointer.playerinfo.common.objects.Correspond;
import com.nullpointer.playerinfo.common.objects.Player;

public class PlayerInfoBukkit extends JavaPlugin {

    public static Plugin plugin;
    public static YamlConfiguration config;
    public static YamlConfiguration level;
    public static Mysql mysql;

    static File dataFolder;
    static MagicYaml magicYaml;
    static YamlConfig configYC;
    static YamlConfig levelCofigYC;

    public static int reconnectionTime;
    public static int serverCode;
    public static Boolean bungeeMode;

    public static Correspond correspond = null;


    @Override
    public void onEnable() {
        plugin = PlayerInfoBukkit.getPlugin(PlayerInfoBukkit.class);

        plugin.getLogger().info("加载配置文件...");
        dataFolder = getDataFolder();
        magicYaml = new MagicYaml(dataFolder, "bukkit", true);

        configYC = magicYaml.saveResource("config.yml", false);

        if (configYC.needUpdate()) {
            configYC.update(false);
        }

        config = configYC.getBukkitConfig();

        bungeeMode = config.getBoolean("bungee_mode");
        reconnectionTime = config.getInt("reconnection_time");
        serverCode = config.getInt("server_code");
        Base.hotUpdate = config.getBoolean("hot_update");

        if (isDatabaseNotConfigured()) {
                getLogger().severe("数据库还未配置，请在config.yml中配置");
                return;
            }

            getLogger().info("初始化数据库..."); //初始化数据库
            mysql = new Mysql(
                config.getString("mysql.host"), 
                config.getInt("mysql.port"), 
                config.getString("mysql.database"), 
                config.getString("mysql.username"), 
                config.getString("mysql.password")
            );
            mysql.connect();

        if (!bungeeMode) { // 判断是否使用Bungee模式

            getLogger().info("注册事件...");
            EventManager.registerEvent();

            getLogger().info("注册命令...");
            Commands cmds = new Commands();
            PluginCommand c = getCommand("playerinfo");
            c.setExecutor(cmds);
            c.setTabCompleter(cmds);

            getLogger().info("读取等级配置...");
            levelCofigYC = magicYaml.saveResource("level.yml", false);
            level = levelCofigYC.getBukkitConfig();

            if (levelCofigYC.needUpdate()) {
                levelCofigYC.update(false);
            }

            // 读取等级
            Base.maxLevel = level.getInt("level.max");
            Base.useOriginalLevel = level.getBoolean("level.upgrade.useOriginal");
            for (int i = 1; i <= level.getInt("level.upgrade.scope"); i++) {
                Base.scopeMap.put(i, level.getIntegerList("level.upgrade.function.scope" + i + ".scope"));
                Base.expMap.put(i, level.getInt("level.upgrade.function.scope" + i + ".exp"));
            }
        }

        runTaskAsynchronously(new Runnable(){
            @Override
            public void run() {
                correspond = new Correspond(
                    config.getString("correspond.host"), 
                    config.getInt("correspond.port"), serverCode) {
                        @Override
                        public void handleMessage(String message) {
                            String[] args = Methods.getArgs(message);
                            Player target = Base.playerMap.get(Bukkit.getPlayer(args[2]).getUniqueId());
                            if (!args[0].equals("0")) return; // 判断是否为bungee发来的信息
                            if (args.length == 3) {
                                if (args[1].equals("removedata")) {
                                    target.removeData();
                                }
                            } else if (args.length == 4) {
                                switch (args[1]) {
                                    case "addexp":
                                        target.addExp(Integer.valueOf(args[3]));
                                        break;
                                    case "removeexp":
                                        target.removeCash(Integer.valueOf(args[3]));
                                        break;
                                    case "addcash":
                                        target.addCash(Integer.valueOf(args[3]));
                                        break;
                                    case "removecash":
                                        target.removeCash(Integer.valueOf(args[3]));
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    };
            }
        });
        
        plugin.getLogger().info("完成!");
        
    }

    @Override
    public void onDisable() {
        if (bungeeMode) return;
        //保存数据
        if (Base.playerMap.size() == 0) {
            return;
        }
        for (Player player : Base.playerMap.values()) {
            try {
                mysql.savePlayer(player);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean isDatabaseNotConfigured() {
        return config.getString("mysql.host").isEmpty() 
            || config.getInt("mysql.port") == 0;
    }

    public static BukkitTask runTaskAsynchronously(Runnable runnable) {
        return plugin.getServer().getScheduler().runTaskAsynchronously(plugin, runnable);
    }

}
